// https://www.bilibili.com/video/BV13jU4YoErU
import * as THREE from 'three'
// 引入轨道控制器扩展库OrbitControls.js
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

const scene = new THREE.Scene()
const cube3 = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial({
      color: 'blue',
    })
)
scene.add(cube3)
cube3.position.set(0, 0, 0)

const size = {
  width: window.innerWidth,
  height: window.innerHeight,
}
const camera = new THREE.PerspectiveCamera(
    75,
    size.width / size.height,
)
camera.position.set(1, 1, 3)
scene.add(camera)

const canvas = document.getElementById('webgl')
const renderer = new THREE.WebGLRenderer({
  canvas: canvas
})
renderer.setSize(size.width, size.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // 适配高DPI屏幕，但最大不超过2

renderer.render(scene, camera)

const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true // 开启阻尼

// 监听窗口大小变化
window.addEventListener('resize', () => {
  const { innerWidth, innerHeight } = window
  // 更新相机的宽高
  camera.aspect = innerWidth / innerHeight
  camera.updateProjectionMatrix() // 更新相机投影矩阵

  // 更新渲染器的宽高
  renderer.setSize(innerWidth, innerHeight)

  // 以防用户将窗口转移到另一个屏幕，所以resize事件也要更新像素比例
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

window.addEventListener('dblclick', () => {
  const fullscreenEl = document.fullscreenElement || document.webkitFullscreenElement
  if (!fullscreenEl) {
    // 当前没有全屏，则进入全屏
    if (canvas.requestFullscreen){
      canvas.requestFullscreen().then(() => {
        console.log('进入全屏')
      })
    } else if (canvas.webkitRequestFullscreen) {
      canvas.webkitRequestFullscreen().then(() => {
        console.log('进入全屏')
      })
    }
  } else {
    // 当前已全屏，则退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen().then(() => {
        console.log('退出全屏')
      })
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen().then(() => {
        console.log('退出全屏')
      })
    }
  }
})

// 手写帧差值方案，保证动画不与帧数挂钩
let time = Date.now()
const frameTick = () => {
  const currentTime = Date.now()
  const delta = currentTime - time
  time = currentTime
  cube3.rotation.z += delta * 0.002
  renderer.render(scene, camera)
  window.requestAnimationFrame(frameTick)
}
frameTick()